package WaitNotify;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2022-12-25
 * Time: 10:54
 */
public class TestDemo5 {

    private static final Object obj = new Object();

    /**
     * wait(n) 与 sleep(n) 的区别
     * 1.wait和sleep虽然都是让线程放弃对CPU的使用权,但是wait(n)在等待期间会释放对象锁而sleep在等待期间不会释放锁
     * 2.wait(n)是object的方法所有对象都能调用,而sleep是Thread类的方法
     * 3.wait强制要与synchronized结合使用否则报错,sleep不强制与synchronized搭配使用
     * 相同点
     * wait(n)和sleep(n)进入的都是TIMED_WAITING状态
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            synchronized (obj){
                System.out.println("t1获得锁");
                try {
                    obj.wait(20000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();

        Thread.sleep(1000);
        synchronized (obj) {
            System.out.println("主线程获得锁");
        }
    }

}
